<template>
  <el-container>
    <el-header height="70px">
      <!-- logo -->
      <div class="logo">
        <img src="@/assets/logo1.png" alt="" />
      </div>
      <!-- title -->
      <!-- <div class="title">{{ title }}</div> -->
      <!-- 用户显示信息 -->
      <div class="user">
        <img src="../../assets/pic.jpg" alt="图片未加载" class="pic" />
        <span class="username">西门吹雪</span>
      </div>
      <template v-if="this.$store.state.exam.isShow">
        <div class="btn">
          <el-button @click="upExam">交卷</el-button>
        </div>
        <div class="time">
          考试限时：{{ examTime }}分钟 倒计时 {{ minutes }}:{{ second }}
        </div>
      </template>
      <template v-else>
        <div class="btn">
          <el-button @click="Exit">退出</el-button>
        </div>
      </template>
    </el-header>
    <el-container>
      <el-aside width="200px">
        <!-- @open="handleOpen"
          @close="handleClose"
          default-active="/exam/single/1"
          :default-active="$route.path"
        -->
        <el-menu
          :default-active="$route.path"
          class="el-menu-vertical-demo"
          active-text-color="#409EFF"
          unique-opened
          router
        >
          <!--
                将:index=“item.path”
                改为:index="item.path + ’ ’ "
                完美解决
                    原因：elementUI的index是字符串格式，加一个‘ ’，将后台数据转换为字符串
             -->
          <el-submenu index="0" v-if="exam[0].topic.length != 0">
            <template slot="title">
              <i class="el-icon-location"></i>
              <span>单选题</span>
            </template>
            <!--
              :index="`/exam/${topic[item.name]}/${$route.params.id}`"
               :index="`/exam/${topic[item.name]}/${topicItem.id}`"
              -->
            <el-menu-item
              :index="`/exam/single/${topicItem.ids}`"
              v-for="topicItem in exam[0].topic"
              :key="0 + '-' + topicItem.ids"
              >题目{{ topicItem.ids }}
            </el-menu-item>
          </el-submenu>
          <el-submenu index="1" v-if="exam[1].topic.length != 0">
            <template slot="title">
              <i class="el-icon-location"></i>
              <span>多选题</span>
            </template>
            <el-menu-item
              :index="`/exam/multiple/${topicItem.ids}`"
              v-for="topicItem in exam[1].topic"
              :key="1 + '-' + topicItem.ids"
              >题目{{ topicItem.ids }}
            </el-menu-item>
          </el-submenu>
          <el-submenu index="2" v-if="exam[2].topic.length != 0">
            <template slot="title">
              <i class="el-icon-location"></i>
              <span>判断题</span>
            </template>
            <el-menu-item
              :index="`/exam/judge/${topicItem.ids}`"
              v-for="topicItem in exam[2].topic"
              :key="2 + '-' + topicItem.ids"
              >题目{{ topicItem.ids }}
            </el-menu-item>
          </el-submenu>
          <!-- <el-submenu index="2">
            <template slot="title">
              <i class="el-icon-menu"></i>
              <span>多选题（每题5分）</span>
            </template>
            <el-menu-item index="/exam/multiple">题目1</el-menu-item>
          </el-submenu>
          <el-submenu index="3">
            <template slot="title">
              <i class="el-icon-menu"></i>
              <span>判断题（每题5分）</span>
            </template>
            <el-menu-item index="/exam/judge">题目1</el-menu-item>
          </el-submenu> -->
        </el-menu>
      </el-aside>
      <el-main>
        <!-- <div class="scoal" v-if="!isShow">总成绩：100</div> -->
        <router-view></router-view>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      examTime: '',
      minutes: '',
      second: 59,
      timeBar: '',
      isfullScreen: true,
      count: 0, // 切屏次数
      title: '',
      answer: {}
    }
  },
  computed: {
    // ...mapState(['Allexam'])
    ...mapState({
      exam: (state) => state.exam.Allexam
    })
  },
  mounted() {
    console.log(this.exam)
    this.examTime = this.$route.query.time
    this.minutes = this.$route.query.time - 1
    this.$store.commit('SETSHOW', this.$route.meta.isShow)
    console.log(this.$store.state.exam.isShow)
    // this.minutes = 0
    // this.minutes = 0
    if (this.$store.state.exam.isShow) {
      console.log('考试中')
      this.countDown()
      // 全屏
      this.fullScreen()
      // 禁止按键
      this.banKey()
      // 禁止鼠标右键
      this.banRightMouse()
      // 是否全屏
      this.isFullscreen()
    }
  },
  beforeDestroy() {
    window.onkeydown = null
    window.onresize = null
    // this.handlerData()
  },
  methods: {
    // 倒计时 顺序不能动
    countDown() {
      let that = this
      // that 负责展示，局部变量second、minutes负责计算
      let second = that.second
      let minutes = that.minutes
      that.minutes = that.minutes < 10 ? '0' + that.minutes : that.minutes
      this.timeBar = setInterval(() => {
        second = second - 1
        if (second < 1) {
          second = 59
          minutes = minutes - 1
          that.minutes = minutes
          that.minutes = that.minutes < 10 ? '0' + that.minutes : that.minutes
        }
        that.second = second
        that.second = that.second < 10 ? '0' + that.second : that.second
        if (minutes < 0) {
          that.minutes = '00'
          that.second = '00'
          clearInterval(that.timeBar)
          that.$alert('请提交试卷', '考试结束', {
            confirmButtonText: '确定',
            callback: () => {
              that.exitFullscreen()
              that.$router.push({ path: '/student/sexam', query: { id: -1 } })
            }
          })
        }
      }, 1000)
    },
    // 交卷前的数据处理：
    handlerData() {
      this.answer = {
        examId: this.$store.state.exam.examId,
        id: this.$store.state.exam.stuId,
        examJoinDate: this.$store.state.exam.examJoinDate,
        // 答案全部要数组形式
        // 单选
        multipleChoiceList: [
          {
            questionId: '',
            questionAnswerOptionIds: '',
            questionTypeDescription: ''
          }
        ],
        // 多选
        moreMultipleChoiceList: [
          {
            questionId: '',
            questionAnswerOptionIds: '',
            questionTypeDescription: ''
          }
        ],
        // 判断
        trueOrFalseList: [
          {
            questionId: '',
            questionAnswerOptionIds: '',
            questionTypeDescription: ''
          }
        ]
      }
      console.log(this.$store.state.exam.answerList)
      let answerList = this.$store.state.exam.answerList
      answerList.forEach((item) => {
        delete item.ids
        item.questionId = item.id
        delete item.id
        item.questionTypeDescription = item.typeId
        delete item.typeId
        if (Array.isArray(item.answer)) {
          item.questionAnswerOptionIds = item.answer
        } else {
          item.questionAnswerOptionIds = [item.answer]
        }
        delete item.answer
      })
      this.answer.multipleChoiceList = answerList.filter((item) => {
        return item.questionTypeDescription == 0
      })
      this.answer.moreMultipleChoiceList = answerList.filter((item) => {
        return item.questionTypeDescription == 1
      })
      this.answer.trueOrFalseList = answerList.filter((item) => {
        return item.questionTypeDescription == 2
      })
      console.log(this.answer)
    },
    // 交卷按钮
    upExam() {
      let isFull =
        document.fullscreenElement ||
        document.webkitRequestFullScreen || // 谷歌
        document.mozRequestFullScreen || // 火狐
        document.msRequestFullScreen // IE11
      this.$confirm(
        `时间还有${this.minutes}:${this.second},你是否要交卷?`,
        '考试提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.$message({
            type: 'success',
            message: '交卷成功!'
          })
          // 交卷请求
          if (isFull) {
            this.exitFullscreen()
          }
          this.handlerData()
          // 跳转页面
          clearInterval(this.timeBar)
          this.$router.push({ path: '/student/sexam', query: { id: -1 } })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
          this.fullScreen()
        })
    },
    // 退出按钮
    Exit() {
      this.$confirm('你是否要退出?', '退出', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$message({
            type: 'success',
            message: '退出成功!'
          })
          // 交卷请求
          this.$router.push({ path: '/teach/exam' })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // https://blog.csdn.net/sinat_33255495/article/details/125069299
    // 全屏
    fullScreen() {
      let de = document.documentElement
      if (de.requestFullscreen) {
        de.requestFullscreen()
      } else if (de.mozRequestFullScreen) {
        de.mozRequestFullScreen()
      } else if (de.webkitRequestFullScreen) {
        de.webkitRequestFullScreen()
      }
    },
    // 退出全屏
    exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
      } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
      }
    },
    // 禁用按键
    banKey() {
      // 监听键盘Esc按键事件
      if (navigator.keyboard) {
        // 禁用esc,f11退出全屏 F5刷新
        navigator.keyboard.lock([
          'Escape',
          'F11',
          'F5',
          'F3',
          'F7',
          'F1'
          // 'F12'
        ])
      }
    },
    // 禁用鼠标右键
    banRightMouse() {
      document.oncontextmenu = function () {
        return false
      }
    },
    /**
     * [isFullscreen 判断浏览器是否全屏]
     * @return [全屏则返回当前调用全屏的元素,不全屏返回false]
     */
    isFullscreen() {
      let that = this
      window.onresize = function () {
        let isFull =
          document.fullscreenElement ||
          document.mozFullScreenElement ||
          document.webkitFullscreenElement ||
          document.msFullscreenElement
        if (isFull) {
          console.log('全屏')
        } else {
          that.upExam()
          that.count++
          console.log(that.count)
          if (that.count >= 3) {
            that.$alert('请提交试卷', '考试结束', {
              confirmButtonText: '确定',
              callback: () => {
                that.$router.push({ path: '/student/sexam', query: { id: -1 } })
              }
            })
          }
          console.log('没有全屏')
        }
      }
    }
  }
}
</script>

<style scoped>
* {
  padding: 0;
  margin: 0;
}
.el-header {
  background-color: #b3c0d1;
  color: #fff;
  background: black;
  line-height: 70px;
}

.el-aside {
  background-color: #fff;
  color: #333;
  line-height: 200px;
  height: 93vh;
}

.el-main {
  background-color: #eee;
  color: #333;
  padding: 20px 10px 50px 25px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}
/* logo */
.logo {
  float: left;
  padding-left: 5px;
}
.logo img {
  height: 70px;
}
/* 标题 */
.title {
  float: left;
  font-size: 50px;
  display: flex;
  padding-left: 600px;
}
/* 显示用户信息 */
.pic {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  vertical-align: center;
}
.user {
  float: right;
  width: 200px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}
.username {
  font-size: 16px;
  color: white;
  margin: 5px;
}
/* 按钮 */
.btn {
  float: right;
  margin-left: 40px;
}
.el-button {
  padding: 0 16px;
  height: 30px;
  background: black;
  color: rgba(255, 0, 0, 0.6);
  border-color: rgba(255, 0, 0, 0.6);
}
.el-button:hover {
  color: rgba(255, 0, 0, 1);
  border-color: rgba(255, 0, 0, 1);
}
/* 时间 */
.time {
  font-size: 18px;
  float: right;
}
/* 成绩 */
.scoal {
  position: fixed;
  right: 200px;
  top: 100px;
  font-size: 50px;
}
</style>
